<template>
  <el-dialog
    :visible.sync="isVisible"
    title="通道设置"
    width="780px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @closed="onClose"
  >
    <div class="dialog-container">
      <el-form ref="loginForm" :model="loginForm" label-width="80px">
        <div
          class="item"
          v-for="(item, index) in loginForm.cameras"
          :key="index"
        >
          <div class="flex-row">
            <el-form-item
              :label="`通道${index + 1}`"
              :prop="`cameras[${index}].channelName`"
              class="channel-input"
              :rules="baseRules.channelName"
            >
              <el-input
                v-model="item.channelName"
                placeholder="请输入通道名称"
              />
            </el-form-item>
            <el-form-item
              label=""
              :prop="`cameras[${index}].cameraId`"
              class="camera-input"
              :rules="baseRules.cameraId"
            >
              <el-input v-model="item.cameraId" placeholder="请输入摄像头ID" />
            </el-form-item>
            <!-- 排序 -->
            <el-form-item
              label=""
              :prop="`cameras[${index}].sort`"
              class="sort-input"
              :rules="baseRules.sort"
            >
              <el-input v-model.number="item.sort" placeholder="请输入排序" />
            </el-form-item>
          </div>
          <el-form-item
            label=""
            :prop="`cameras[${index}].channelUrl`"
            class="video-input"
            :rules="baseRules.channelUrl"
          >
            <el-input v-model="item.channelUrl" placeholder="请输入视频地址" />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div slot="footer">
      <el-button @click="onClose">关闭</el-button>
      <el-button type="primary" @click="onSave">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createCamera } from '@/api/camera.js';

export default {
  name: 'LoginDialog',
  data() {
    return {
      isVisible: false,
      loginForm: {
        cameras: [
          { channelName: '', channelUrl: '', cameraId: '', sort: 1 },
          { channelName: '', channelUrl: '', cameraId: '', sort: 2 },
          { channelName: '', channelUrl: '', cameraId: '', sort: 3 },
          { channelName: '', channelUrl: '', cameraId: '', sort: 4 },
          { channelName: '', channelUrl: '', cameraId: '', sort: 5 },
          { channelName: '', channelUrl: '', cameraId: '', sort: 6 },
        ],
      },
      baseRules: {
        channelName: [
          {
            required: true,
            message: '请输入通道名称',
            trigger: ['blur', 'change'],
          },
        ],
        channelUrl: [
          {
            required: true,
            message: '请输入视频地址',
            trigger: ['blur', 'change'],
          },
          {
            type: 'url',
            message: '请输入正确的视频地址',
            trigger: ['blur', 'change'],
          },
        ],
        cameraId: [
          {
            required: true,
            message: '请输入摄像头ID',
            trigger: ['blur', 'change'],
          },
        ],
        sort: [
          {
            required: true,
            message: '请输入排序',
            trigger: ['blur', 'change'],
          },
          {
            type: 'number',
            message: '请输入数字',
            trigger: ['blur', 'change'],
          },
          {
            validator: (rule, value, callback) => {
              if (typeof value !== 'number' || value < 1 || value > 6) {
                callback(new Error('只能是1到6之间的数字'));
              } else {
                const sorts = this.loginForm.cameras.map((item) => item.sort);
                const uniqueSorts = new Set(sorts);
                if (uniqueSorts.size !== sorts.length) {
                  callback(new Error('排序不能重复'));
                } else {
                  callback();
                }
              }
            },
            trigger: ['blur', 'change'],
          },
        ],
      },
    };
  },
  props: {
    cameraAllInfo: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  methods: {
    /**
     * 显示登录对话框
     */
    async show() {
      // console.log(this.cameraAllInfo);
      this.isVisible = true;
      if (this.cameraAllInfo.length !== 0) {
        this.loginForm.cameras = [...this.cameraAllInfo];
      }

      // try {
      //   const res = await getCameraList();
      //   if (res.code === 200 && res.data.length > 0) {
      //     this.loginForm.cameras = res.data.map(item => {
      //       return {
      //         id: item.id,
      //         cameraId: item.camera_id,
      //         channelName: item.name,
      //         channelUrl: item.video_url,
      //         sort: item.sort,
      //       }
      //     });
      //     console.log(res);
      //   }
      // } catch (error) {
      //   console.log(error);
      // }

      // this.loginForm = JSON.parse(localStorage.getItem('channels')) || this.loginForm;
      // this.loginForm = {
      //   // rtmp://24.tcp.cpolar.top:10074/live/test
      //   // https://www.w3school.com.cn/i/movie.mp4
      //   channelOne: 'rtmp://24.tcp.cpolar.top:10074/live/test',
      //   channelTwo: 'https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209105011F0zPoYzHry.mp4',
      //   channelThree: 'https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209104902N3v5Vpxuvb.mp4',
      //   channelFour: 'https://www.w3school.com.cn/example/html5/mov_bbb.mp4',
      //   channelFive: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
      //   channelSix: 'https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8',
      // }
    },
    /**
     * 隐藏
     */
    onClose() {
      this.isVisible = false;
      // 清除表单校验
      this.$refs.loginForm.resetFields();
    },
    /**
     * 保存
     */
    onSave() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) {
          return false;
        } else {
          try {
            const arr = this.loginForm.cameras.map((item) => {
              return {
                id: item.id,
                camera_id: item.cameraId,
                name: item.channelName,
                video_url: item.channelUrl,
                sort: item.sort,
              };
            });
            const res = await createCamera({
              cameras: arr,
            });
            if (res.code === 200) {
              this.isVisible = false;
              // 刷新当前页面
              location.reload();
              this.$message.success(res.msg);
            }
          } catch (error) {
            this.$message.error(error.msg);
            console.error(error);
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.item {
  display: flex;
  flex-direction: column;
  .flex-row {
    display: flex;
    flex-direction: row;
  }
  .channel-input {
    width: 50%;
  }

  .camera-input {
    width: 30%;
    ::v-deep .el-form-item__content {
      margin-left: 20px !important;
    }
  }

  .sort-input {
    width: 20%;
    ::v-deep .el-form-item__content {
      margin-left: 20px !important;
    }
  }
}
</style>
